<?php

class ItemsController extends Controller {

    public function init() {
		$this->layout = '//layouts/left_sidebar_content_right_sidebar';

		parent::init();
    }

    public function actionIndex() {
		$item = $this->__check_get_params_items();

		//батьківська категорія
		$parent_category = Items::model()->findByPk($item->parent_id);

		//головна категорія
		$parent_parent_category = Items::model()->findByPk($parent_category->parent_id);

		//сосідні категорії
		$sibling_categories = Items::model()->findAll('parent_id =:parent_id and type_position =:type_position ', array(':parent_id' => $parent_category->parent_id, ':type_position' => Items::STATUS_TYPE_POSITION_FOLDER));

		$this->sidebar_left_category_content = $this->renderPartial('/category/sidebar_left_children_category', array('category' => $parent_parent_category, 'children_categories' => $sibling_categories, 'active_category' => $parent_category), true);

		$this->render('index', array(
			'item' => $item,
		));
    }

		private function __check_get_params_items() {
			if (Yii::app()->request->getQuery('item_id', 0) && Yii::app()->request->getQuery('item_title', '')) {
				$item = Items::model()->find(
					'type_position = :type_position and status =:status and id =:id', array(
				':id' => Yii::app()->request->getQuery('item_id'),
				':type_position' => Items::STATUS_TYPE_POSITION_ITEM,
				':status' => Items::STATUS_ON_SITE)
				);

				if (empty($item)){
					$this->redirect(Yii::app()->controller->createUrl('error/index'));
				}

				if (!empty($item) && Helper::replace_url($item->title) == Helper::replace_url(Yii::app()->request->getQuery('item_title', ''))){
					//$this->redirect(Yii::app()->controller->createUrl('/items/index', array('item_id' => trim($item->id), 'item_title' => trim($item->title))), true, 301);
					return $item;
				}elseif (!empty($item) && Helper::replace_url($item->title) != Helper::replace_url(Yii::app()->request->getQuery('item_title', ''))){
					$this->redirect(Yii::app()->controller->createUrl('/items/index', array('item_id' => trim($item->id), 'item_title' => $item->title)), true, 301);
				}else{
					$this->redirect(Yii::app()->controller->createUrl('error/index'));
				}
			} else{
				$this->redirect(Yii::app()->controller->createUrl('error/index'));
			}
		}

}
